<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Change Password</title>
		
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	
	<script type="text/javascript">
		function back(system) {
			if(system=="admin"){
				document.location.href = "admin_home.jsp";
			}else if(system=="curriculum"){
				document.location.href = "curriculum_home.jsp";
			}else if(system=="enroll"){
				document.location.href = "enroll_home.jsp";
			}else if(system=="student"){
				document.location.href = "student_home.jsp";
			}
		}
	</script>
</head>
<body>

<%
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}		
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}

	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620");//////"&characterEncoding=tis620" Encoding Thai);
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	String mode = request.getParameter("mode");
	System.out.println("mode: "+mode);
	
	String system = request.getParameter("system");
	System.out.println("system: "+system);

%>

    <div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>

				<div id="main-content-ac">
						
						<table style="border: 0px;">
							<tr style="border: 0px">
								<td style="border: 0px">
									<div class="imageFrame">เปลี่ยนรหัสผ่าน</div>
								</td>
							</tr>
						</table>
						
						<br/><br/><br/><br/>
							<center>
								<div class="CSSTableGenerator">
									<table border="1" width="800px">
										<form id="form" name="form" method="post" action="">
												<tr style="font-size:24px">
													<td><strong>ชื่อผู้ใช้งาน</strong></td>
													<td><input type="text" name="username" id="username" style="font-size: 18px;" value="<%=strUser %>" readonly="readonly"/></td>
											  </tr>
										
											  <tr style="font-size:24px">
													<td><strong>รหัสผ่านเก่า</strong></td>
													<td><input type="password" name="passwordOld" id="passwordOld" style="font-size: 18px;" required/></td>
											  </tr>
									 
											  <tr style="font-size:24px">
													<td><strong>รหัสผ่านใหม่</strong></td>
													<td><input type="password" name="passwordNew" id="passwordNew" style="font-size: 18px;" required/></td>
											  </tr>
											  
											  <tr style="font-size:24px">
													<td><strong>ยืนยันรหัสผ่านใหม่</strong></td>
													<td><input type="password" name="passwordNewRe" id="passwordNewRe" style="font-size: 18px;" required/></td>
											  </tr>
											  <input type="hidden" id="mode" name="mode" value="<%=mode%>" />
<% 
////////////////////////////////GEN SALT//////////////////////////////////////////////////////
						             	SaltGen saltz = new SaltGen();
						             	String salt = saltz.genTimeStamp();
						             	System.out.println("salt: "+salt);
%>
						             <input type="hidden" id="salts" name="salts" value="<%=salt %>" />
											  <tr>
												  <td><center><input type="submit" name="save" id="save" value="save" class="buttonStyle"/></center></td>
										</form>
												  <td><input type="button" name="cancel" id="cancel" value="cancel" onclick="back('<%=system %>')" class="buttonStyle" /></td>
											  </tr>
									</table>
								</div>
							</center>

						
						<br><br><br><br><br><br><br><br>
					
				</div>	
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

<%
		String checkButton = request.getParameter("save");

		// check save button is pressed
		if("save".equals(checkButton)) {
			//get new salt & mode
			String newSalt = request.getParameter("salts");
			String modeSys = request.getParameter("mode");
			System.out.println("modeSys: "+modeSys);
			
			// get value from tag
			String passwordOld = request.getParameter("passwordOld");
			String passwordNew = request.getParameter("passwordNew");
			String passwordNewRe = request.getParameter("passwordNewRe");
			
			
			System.out.println("passwordOld : "+passwordOld);////////////try//////////////
			System.out.println("passwordNew : "+passwordNew);////////////try//////////////
			System.out.println("passwordNewRe : "+passwordNewRe);////////////try//////////////
			System.out.println("newSalt : "+newSalt);////////////try//////////////
			
			//Find old Salt in DB
				ResultSet rs_salt = connect.createStatement().executeQuery("SELECT `username` ,`salt`" 
						+ " FROM user " 
						+ " WHERE username='" + strUser +"'");
					
				rs_salt.next();
				String oldSalt = rs_salt.getString("salt");		
				System.out.println("oldSalt: "+oldSalt);////////////////try/////////////////
			
			/* encrypt password */
			String oldPasswordSalt = passwordOld + oldSalt;
			String newPasswordSalt = passwordNew + newSalt;
					
			String passwordOldEncrypt = PasswordHandler.encryptPassword(oldPasswordSalt);
			String passwordNewEncrypt = PasswordHandler.encryptPassword(newPasswordSalt);
			
			try {			   
				ResultSet rs = connect.createStatement().executeQuery("SELECT username " 
					+ " FROM user " 
					+ " WHERE username='" + strUser +"' AND password='" + passwordOldEncrypt + "'");
				
				rs.last();
				if(rs.getRow() == 1) {
					System.out.println("FIN");///////////try//////////////	
					
					if(passwordOld.equals(passwordNew)) {
%>
						<script language="javascript"> alert("รหัสผ่านเก่าและรหัสผ่านใหม่เหมือนกัน โปรดลองอีกครั้ง");	</script>
<%						
					}
					else {
						if(passwordNew.equals(passwordNewRe)) {
							
							try {					 
								connect.createStatement().executeUpdate("UPDATE `user` SET `password`='" + passwordNewEncrypt + "', `salt`='" + newSalt + "' "
										+ " WHERE username='"+strUser+"'" );
							
%>
								<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ ");	</script>
							<%
							if(modeSys.equals("admin")){
							%>	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp">
							<%}else if(modeSys.equals("curriculum")){ %>	
								<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=curriculum_home.jsp">
							<%}else if(modeSys.equals("enroll")){ %>
								<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=enroll_home.jsp">
							<%}else if(modeSys.equals("student")){ %>
								<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_home.jsp">	
<%
							}
							} catch (SQLException e) {
								e.printStackTrace();
							}	
			
						}
						else {
%>
							<script language="javascript"> alert("รหัสผ่านใหม่กับยืนยันรหัสผ่านใหม่ไม่ตรงกัน โปรดลองอีกครั้ง");	</script>
<%										
						}
					}
				}
				else {
%>
					<script language="javascript"> alert("รหัสผ่านเก่าที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง");	</script>
<%					
				}
				
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		connect.close();
%>

</body>
</html>